package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

     @Autowired
     private WeChatProperties weChatProperties;

     @Autowired
     private UserMapper userMapper;



    /**
     *  登录实现
     * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {
        //1.调用自己创建的私有方法获取微信用户的openid(用户的唯一标识)
        String openId = getOpenId(dto.getCode());
            //判断openId是否存在
        if (openId==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //2.通过openId从数据库中获取对应的用户
       User user = userMapper.getById(openId);
            //如果数据库中没有该用户，需要插入该用户的数据（自动注册）
            if (user==null){
                user = User.builder()
                        .openid(openId)
                        .createTime(LocalDateTime.now())
                        .build();

              //  插入该用户的数据
                userMapper.insert(user);
            }
        //3.用户数据返回到controller
        return user;
    }

    /**
     *      自定义方法，获取openId（用户的唯一标识）
     * @param code 前端发过来的授权码
     * @return  openid
     */
    private String getOpenId(String code) {
        //加个final不会改变数据     微信后台的连接
        final String url="http://api.weixin.qq.com/sns/jscode2session";

        //使用HttpClient去请求微信的后台，获取openId
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //访问微信后台，获取openId
        String json = HttpClientUtil.doGet(url,map);
        log.info("微信登录后台返回的结果：{}",json);

        //将JSON字符串转换为JSON对象，再通过openId键去获值
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("openid解析成功：{}",openid);
        return openid;
    }
}
